<?php

include("Commons.php");

loginRequired( getTerm('parceling', 'parceling') );

$action = param('ac');
$draftid = 0;
$sentflag = 0;
$userid = $_SESSION['user'];

debug('Action : '. $action);

if ( $action=='goto' )
{
	$folder = trim($_POST['toFolder']);
	
	$path = '/parceling/';
	if ( $folder!='' )
		$path .= $folder.'/';

	redirect( formatUrl($path) );
}
elseif ( $action==getTerm('parceling','delete_parcel') || $action==getTerm('parceling','delete_draft') )
{
	$parcelid = param('mid');
	
	query("DELETE FROM parcel WHERE id='$parcelid' AND visibleby='$userid';");

	$_SESSION['parcel'] = getTerm('parceling', 'parcel_deleted');
}

elseif ( $action==getTerm('parceling','report_parcel') )
{
	$parcelid = param('mid');

	$rh = query("SELECT `from` FROM parcel WHERE id='$parcelid';");
	list($sender_id) = mysql_fetch_array($rh);

	$rh = query("SELECT COUNT(DISTINCT reporter_id) FROM reports WHERE report_date > DATE_SUB(NOW(), INTERVAL 48 HOUR) AND reported_id = $sender_id");
	list($reports) = mysql_fetch_array($rh);

	if ($reports >= 2) {
		query("UPDATE `user` SET `banned`=1 WHERE `id`=$sender_id;");
		query("DELETE FROM `reports` WHERE `reported_id`=$sender_id;");
		query("DELETE FROM `parcel` WHERE `from`=$sender_id;");
	} else {
		query("INSERT IGNORE INTO reports (reporter_id,reported_id,parcel_id,report_date) VALUES ('$userid','$sender_id','$parcelid', NOW());");
	}

	$_SESSION['parcel'] = getTerm('parceling','report_sent');

}

elseif ( $action==getTerm('parceling','delete_selected_parcels') || $action==getTerm('parceling','delete_selected_drafts') )
{
	$selection = $_POST['selection'];
	
	foreach ($selection as $mid)
		if ( is_numeric($mid) )
			query("DELETE FROM parcel WHERE id='$mid' AND visibleby='$userid';");

	$_SESSION['parcel'] = getTerm('parceling', 'parcels_deleted');
	
	redirect( formatUrl('/parceling/') );
}
elseif ( $action==getTerm('parceling', 'save_as_draft') )
{
	$username = param('username');
	$subject = param('subject');
	$parcel = param('parcel');

	query("INSERT INTO `parcel` (`from`,`toname`,`date`,`subject`,`parcel`,`draftflag`,`visibleby`,processed) VALUES ('$userid', '$username', NOW(), '$subject', '$parcel',1,'$userid',1);");

	$_SESSION['parcel'] = getTerm('parceling', 'parcel_saved');
	
	redirect( formatUrl('/parceling/') );
}
elseif ( $action==getTerm('parceling', 'save_draft') )
{
	$username = param('username');
	$subject = param('subject');
	$parcel = param('parcel');
	$draftid = param('did');

	query("	UPDATE	`parcel`
			SET		`toname`='$username',
					`date`=NOW(),
					`subject`='$subject',
					`parcel`='$parcel'
			WHERE	`id`='$draftid'
			AND		`visibleby`='$userid';");

	$_SESSION['parcel'] = getTerm('parceling', 'parcel_saved');
	
	redirect( formatUrl('/parceling/') );
}
elseif ( $action==getTerm('parceling', 'send_parcel') )
{

	$username = param('username');
	$subject = param('subject');
	$parcel = param('parcel');
	
	if ( empty($username) )
		$usernameerror = getTerm('parceling', 'no_username');
	
	elseif ( ! eregi('^[a-zA-Z0-9_]+$', $username) )
		$usernameerror = fill( getTerm('parceling', 'invalid_username') , $username );
		
	else
	{
		$rh = query("	SELECT	id,username,email
						FROM	user
						WHERE	username='$username';");
				
		if ( mysql_num_rows($rh)==0 )
			$usernameerror = fill( getTerm('parceling', 'username_doesnt_exist') , $username );
		
		else
			list($usernameid, $toname, $tomail) = mysql_fetch_array($rh);
			
		if ( $usernameid==$userid )
			$usernameerror = getTerm('parceling', 'cannot_send_to_yourself');
	}
	
		
	if ( empty($subject) )
		$subjecterror = getTerm('parceling', 'no_subject');
		
	if ( empty($parcel) )
		$parcelerror = getTerm('parceling', 'no_parcel');
		
	list($left, $limit) = check_parcels($userid);
	if ($left <= 0) {
		$parcelerror = getTerm('parceling', 'limit_reached');
	}

	if ( !empty($usernameerror) || !empty($subjecterror) || !empty($parcelerror) )
		$action = 'send';
		
	else {
		if ( hasValidProfile($userid) && !isBanned($userid)) {
			query("	INSERT INTO parcel
						(`from`,`to`,`toname`,`date`,`subject`,`parcel`,`draftflag`,`visibleby`,`processed`)
				VALUES	('$userid', '$usernameid', '$username', NOW(), '$subject', '$parcel',0,'$userid',0) ;");
			processUserParcels($userid);
		} else {
			$_SESSION['parcel'] = fill( getTerm('parceling', 'parcel_sent') , $username);
		}

			
		if ( array_key_exists('did', $_POST) )
		{
			$draftid = param('did');
			query("	DELETE FROM parcel
					WHERE id='$draftid' AND visibleby='$userid';");
		}
	
		redirect( formatUrl('/parceling/') );
	}
}
elseif ( $action=='read' )
{
    $parcelid = param('parcel');
	
    $rh = query("   SELECT m.id as 'parcelid',subject,date,parcel,u.username AS 'sender',u.id AS 'senderid',m.toname AS 'recipient',draftflag
                    FROM parcel m
                    JOIN user u ON m.from=u.id
                    WHERE m.id=$parcelid
                    AND m.visibleby=$userid
                    ORDER BY date DESC;");
                    
    if ( mysql_num_rows($rh)>0 )
    {
        $parcel = mysql_fetch_assoc($rh);
        
        if ( $parcel['draftflag']==1 )
        {
            $username = $parcel['recipient'];
            $subject = $parcel['subject'];
            $draftid = $parcel['parcelid'];
            $parcelid = $parcel['parcelid'];
            $parcel = $parcel['parcel'];
	
            $action = "send";
        }
        else
        {
			if ( $parcel['senderid']==$userid )
				$sentflag = 1;

	        $date = formatDate($parcel['date']);
	        $time = formatTime($parcel['date']);
            $parcelid = $parcel['parcelid'];
			$sender = '<a href="'. formatUrl('/profile/'. $parcel['sender']) .'">'. $parcel['sender'] .'</a>';
			$recipient = '<a href="'. formatUrl('/profile/'. $parcel['recipient']) .'">'. $parcel['recipient'] .'</a>';
			$subject = $parcel['subject'];
	        $parcel = str_replace("\n", "<br/>", $parcel['parcel']);
        }
    }
}
elseif ( $action==getTerm('parceling', 'reply_parcel') )
{
    $parcelid = param('parcel');
    
    $rh = query("   SELECT subject,parcel,u.username AS 'sender'
                    FROM parcel m
                    JOIN user u ON m.from=u.id
                    WHERE m.id=$parcelid
                    AND m.visibleby=$userid
                    ORDER BY date DESC;");
                    
    if ( mysql_num_rows($rh)>0 )
    {
    	$parcel = mysql_fetch_assoc($rh);
		redirect( formatUrl('/parceling/send/'. $parcel['sender']) );
    }
}

if ( $action=='read' )
{
	pushNavigationItem( getTerm('parceling', 'parceling'), '/parceling/' );
	
	if ( $sentflag==1 )
    	pushNavigationItem( getTerm('parceling', 'sent_items'), '/parceling/sent/' );
  
    pushNavigationItem( $subject, '/parceling/parcel-'. $parcelid .'.html' );

    printHeader( getTerm('base', 'site_name') , $subject, 'parceling' );

	print "<form action=\"${_SERVER[REQUEST_URI]}\" method=\"post\">";
	
    print '<div>'. getTerm('parceling', 'from') .' : '. $sender .'</div>';
    print '<div>'. getTerm('parceling', 'to') .' : '. $recipient .'</div>';
    print '<div>'. getTerm('parceling', 'date') .' : '. $date .', '. $time .'</div>';
    print '<p>'. $parcel .'</p>';
    
	print '<div class="field">';
	
	if ( $sentflag==0 )
		print '<input type="submit" name="ac" value="'. getTerm('parceling', 'reply_parcel') .'" /> ';
	
	print '<input type="submit" name="ac" value="'. getTerm('parceling', 'delete_parcel') .'" />';
	print '<input type="hidden" name="mid" value="'.$parcelid.'" />';
	print '<p align="right"><input type="submit" name="ac" value="'. getTerm('parceling', 'report_parcel') .'" />';
	print '</div>';
	print '</form>';

    printFooter();
}
elseif ( $action=='send' )
{
	pushNavigationItem( getTerm('parceling', 'parceling'), '/parceling/' );
	
	if ( $draftid==0 )	
	{
		$username = param('username');
		pushNavigationItem( getTerm('parceling', 'send_a_parcel'), '/parceling/send/' );
	}
	else
	{
		pushNavigationItem( getTerm('parceling', 'drafts'), '/parceling/drafts/' );
		pushNavigationItem( fill( getTerm('parceling', 'send_modify_draft'), $username ) , '/parceling/drafts/' );
	}
	
	printHeader( getTerm('base', 'site_name') , fill( getTerm('parceling', 'send_parcel_to'), $username ), 'parceling' );

	print "<form action=\"${_SERVER[REQUEST_URI]}\" method=\"post\">";

	if ( $draftid>0 )
		print '<input type="hidden" name="did" value="'. $draftid .'" />';

	print "<div class=\"field". (empty($usernameerror) ? '' : ' error') ."\"><label for=\"username\">" . getTerm('parceling', 'to') . "</label>";
	print (empty($usernameerror) ? '' : "<div class=\"error-hint\">$usernameerror</div>");
	print "<input type=\"text\" id=\"username\" name=\"username\" value=\"$username\" />";
	print "</div>";
	
	print "<div class=\"field". (empty($subjecterror) ? '' : ' error') ."\"><label for=\"subject\">" . getTerm('parceling', 'subject') . "</label>";
	print (empty($subjecterror) ? '' : "<div class=\"error-hint\">$subjecterror</div>");
	print "<input type=\"text\" id=\"subject\" name=\"subject\" value=\"$subject\" />";
	print "</div>";
	
	print "<div class=\"field". (empty($parcelerror) ? '' : ' error') ."\"><label for=\"parcel\">" . getTerm('parceling', 'your_parcel') . "</label>";
	print (empty($parcelerror) ? '' : "<div class=\"error-hint\">$parcelerror</div>");
	print "<textarea id=\"parcel\" name=\"parcel\">". $parcel ."</textarea>";
	print "</div>";
		
	print '<div class="field"><input type="submit" name="ac" value="' . getTerm('parceling', 'send_parcel') . '" /> <input type="submit" name="ac" value="' . getTerm('parceling', ($draftid==0 ? 'save_as_draft' : 'save_draft') ) . '" />';
	
	if ( $draftid>0 )
		print ' <input type="submit" name="ac" value="'. getTerm('parceling', 'delete_draft') .'" />';
	print '<br>';

	list($left, $limit) = check_parcels($userid);

	$limit_parcel = fill(getTerm('parceling', 'limit_state'), $left, $limit);
	echo "<br>$limit_parcel";

	print '</div>';
	
	print "</form>";
	
	printFooter();
}
elseif ( $action=='send' )
{
	redirect('..');
}
else
{
	$currentFolder = array_key_exists('folder', $_GET) ? $_GET['folder'] : 'receive';
	
	pushNavigationItem( getTerm('parceling', 'parceling'), '/parceling/' );
	
	$sentflag = 0;
	
	if ( $currentFolder=='receive' )
	{
		$sql = "SELECT m.id,subject,date,username
				FROM parcel m
				JOIN user s ON m.from=s.id
				WHERE m.to='$userid'
				AND m.visibleby='$userid'
				AND m.draftflag=0
				ORDER BY date DESC;";
				
		$sentflag = 0;
	}
	elseif ( $currentFolder=='sent' )
	{
		pushNavigationItem( getTerm('parceling', 'sent_items'), '/parceling/sent/' );
		
		$sql = "SELECT m.id,subject,date,m.toname AS 'username'
				FROM parcel m
				WHERE m.from='$userid'
				AND m.visibleby='$userid'
				AND m.draftflag=0
				ORDER BY date DESC;";
				
		$sentflag = 1;
	}
	elseif ( $currentFolder=='drafts' )
	{
		pushNavigationItem( getTerm('parceling', 'drafts'), '/parceling/drafts/' );
		
		$sql = "SELECT m.id,m.subject,m.date,m.toname AS 'username'
				FROM parcel m
				WHERE m.from='$userid'
				AND m.visibleby='$userid'
				AND m.draftflag=1
				ORDER BY date DESC;";
				
		$sentflag = 1;
	}
	
	printHeader( getTerm('base', 'site_name') , getTerm('parceling', 'parceling'), 'parceling' );

	if ( ! empty($_SESSION['parcel']) )
	{
		print "<div class=\"information\">". $_SESSION['parcel'] ."</div>";
		$_SESSION['parcel'] = '';
	}
	
	$folders = array();
	$folders['receive'] = '';
	$folders['sent'] = 'sent';
	$folders['drafts'] = 'drafts';
	
	print '<div id="jump" class="box"><p>';
	print '<form action="'. $_SERVER['REQUEST_URI'] .'" method="post">';
	print '<label for="toFolder">'. getTerm('parceling','go_to') .'</label>';
	print '<input type="hidden" name="ac" value="goto" />';
	print '<select name="toFolder" id="toFolder">';
	foreach ($folders as $label => $folder)
		print '<option value="'. $folder .'"'. ($currentFolder==$folder ? ' selected="selected"' : '') .'>'. getTerm('parceling',$label) .'</option>';
	print '</select>';
	print '<input type="submit" value="'. getTerm('parceling','go') .'" />';
	print '</form>';
	print '</p></div>';
	
	$rh = query($sql);
	
	print '<div id="parcels" class="box">';
	print '<form action="'. $_SERVER['REQUEST_URI'] .'" method="post">';
	print '<table>';
	print '<tr><th class="selection-col"></th><th class="subject-col">'. getTerm('parceling','subject') .'</th><th class="sender-col">'. getTerm('parceling', ($sentflag ? 'to' : 'from')) .'</th><th class="date-col">'. getTerm('parceling','date') .'</th></tr>';
	
	if ( mysql_num_rows($rh)!=0 )
	{
	
		while ( $parcel = mysql_fetch_assoc($rh) )
		{
			$username = '<a href="'. formatUrl('/profile/'. $parcel['username']) .'">'. $parcel['username'] .'</a>';
			$subject = '<a href="'. formatUrl('/parceling/parcel-'. $parcel['id'] .'.html') .'">'. $parcel['subject'] .'</a>';
			$date = formatDate($parcel['date']);
			$time = formatTime($parcel['date']);
			$mid = $parcel['id'];
			
			print "<tr><td><input type=\"checkbox\" name=\"selection[]\" value=\"$mid\" /></td><td>$subject</td><td>$username</td><td>$date, $time</td></tr>";
			
		}
	
		print '</ul></li>';
	
	}
	else
	{
		print '<tr><td colspan="4"><p class="no-parcel">'. getTerm('parceling','no_parcel_in_folder') .'</p></td></tr>';
	}
	
	print '<tr><td colspan="4" class="action-row"><input type="submit" name="ac" value="'. getTerm('parceling', ($currentFolder=='drafts' ? 'delete_selected_drafts' : 'delete_selected_parcels') ) .'" /></tr>';
	print '</table>';
	print '</form>';
	print '</div>';

	printFooter();
}



function check_parcels($userid) {

$premium_limit = 100;
$limited_countries = array(
	100, #india
	163, #pakistan
);

$parcels_common = array(5, 10, 20);
$parcels_limited = array(2, 3, 5);

$time_limits = array(3, 12, 9999);

	$values = $parcels_common;

	$rh = query("SELECT country FROM profile WHERE user=$userid AND valid IS NOT NULL;");
	
	if (mysql_num_rows($rh) > 0 ) {
		list($country) = mysql_fetch_array($rh);

		if (in_array($country, $limited_countries)) {
			$values = $parcels_limited;
		}
	}
	$limits = array_combine($time_limits, $values);

	$rh = query("SELECT premium,TIMESTAMPDIFF(DAY, since, NOW()) from `user` WHERE id=$userid");
	list($premium, $days) = mysql_fetch_array($rh);

	$rh = query("SELECT COUNT(*) FROM `parcel` WHERE `from` = $userid AND `visibleby` = $userid AND `draftflag` = 0 AND `date` BETWEEN CONCAT(CURDATE(), ' ', '00:00:00') AND CONCAT(CURDATE(), ' ', '23:59:59')");
	list($sent) = mysql_fetch_array($rh);

	$limit = 5;

	if ($premium == 1) {
		$limit = $premium_limit;
	} else {
		foreach ($limits as $months => $val) {
			if ($num < $months) {
				$limit = $val;
				break;
			}
		}
	}

	$left = $limit - $sent;
	return array($left, $limit);
}


?>
